<template>
  <div id="mapDiv"></div>
  <div style="display: grid; grid-template-columns: 50% 50%">
    <div class="app-container">
      <div class="list">标记列表</div>
      <el-table
        v-loading="loading"
        :data="MapDataList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="位置" align="center" prop="position" />
        <el-table-column label="背景" align="center">
          <template #default="scope">
            <img
              style="width: 50%"
              :src="selectImage(scope.row.color)"
              alt=""
            />
          </template>
        </el-table-column>
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="类型" align="center">
          <template #default="scope">
            <span v-if="scope.row.type === 'type1'">空</span>
            <span v-else-if="scope.row.type === 'type2'">跳转链接</span>
            <span v-else-if="scope.row.type === 'type3'">图片</span>
            <span v-else-if="scope.row.type === 'type4'">视频</span>
            <span v-else-if="scope.row.type === 'type5'">富文本</span>
          </template>
        </el-table-column>
        <el-table-column label="内容" align="center" prop="content" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改地图对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
        <el-form
          ref="MapDataRef"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="地理坐标" prop="position">
            <el-input
              v-model="form.position"
              placeholder="请输入地理坐标"
              disabled
            />
          </el-form-item>
          <el-form-item label="标记颜色" prop="color">
            <el-radio-group v-model="form.color">
              <el-radio-button label="黄色背景" value="yellow" />
              <el-radio-button label="蓝色背景" value="blue" />
              <el-radio-button label="绿色背景" value="green" />
            </el-radio-group>
            <div class="color-preview">
              <img :src="selectImage(form.color)" alt="" />
            </div>
          </el-form-item>
          <el-form-item label="标记标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标记标题" />
          </el-form-item>
          <el-form-item label="标记类型" prop="type">
            <el-radio-group v-model="form.type">
              <el-radio-button label="空" value="type1" />
              <el-radio-button label="跳转链接" value="type2" />
              <el-radio-button label="图片" value="type3" />
              <el-radio-button label="视频" value="type4" />
              <el-radio-button label="富文本" value="type5" />
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="标记内容"
            prop="content"
            v-if="form.type !== 'type1'"
          >
            <el-input
              v-model="form.content"
              placeholder="请输入跳转链接"
              v-if="form.type === 'type2'"
            />
            <image-upload
              :limit="1"
              v-model="form.content"
              v-if="form.type === 'type3'"
            />
            <video-upload v-model="form.content" v-if="form.type === 'type4'" />
            <editor
              v-model="form.content"
              :min-height="200"
              v-if="form.type === 'type5'"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div class="app-container">
      <div class="list">
        <div>边界列表</div>
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >添加边界</el-button
        >
      </div>
      <el-table v-loading="loading" :data="boundaryList">
        <el-table-column label="标题" align="center" prop="title" />
        <el-table-column label="线颜色" align="center" prop="color" />
        <el-table-column label="线宽" align="center" prop="weight" />
        <el-table-column label="线的透明度" align="center" prop="opacity" />
        <el-table-column label="背景颜色" align="center" prop="fillColor" />
        <el-table-column label="背景透明度" align="center" prop="fillOpacity" />
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              icon="Edit"
              @click="bhandleUpdate(scope.row)"
              v-hasPermi="['boundary:boundary:edit']"
              >修改</el-button
            >
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="bhandleDelete(scope.row)"
              v-hasPermi="['boundary:boundary:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="btotal > 0"
        :total="btotal"
        v-model:page="bqueryParams.pageNum"
        v-model:limit="bqueryParams.pageSize"
        @pagination="bgetList"
      />
      <el-dialog :title="title" v-model="bopen" width="600px" append-to-body>
        <el-form ref="boundaryRef" :model="boundaryConfig" label-width="100px">
          <el-form-item label="边界标题" prop="title">
            <el-input v-model="boundaryConfig.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="线颜色" prop="color">
            <el-input
              v-model="boundaryConfig.color"
              placeholder="请输入线颜色"
              type="color"
            />
          </el-form-item>
          <el-form-item label="线宽" prop="weight">
            <el-input-number
              style="width: 200px"
              v-model="boundaryConfig.weight"
              placeholder="请输入线宽"
              type="number"
              :min="0"
            />
          </el-form-item>
          <el-form-item label="线的透明度" prop="opacity">
            <el-input-number
              style="width: 200px"
              v-model="boundaryConfig.opacity"
              placeholder="请输入线的透明度"
              type="number"
              :min="0"
              :step="0.1"
              :max="1"
            />
          </el-form-item>
          <el-form-item label="背景颜色" prop="fillColor">
            <el-input
              v-model="boundaryConfig.fillColor"
              placeholder="请输入背景颜色"
              type="color"
            />
          </el-form-item>
          <el-form-item label="背景透明度" prop="fillOpacity">
            <el-input-number
              style="width: 200px"
              v-model="boundaryConfig.fillOpacity"
              placeholder="请输入背景透明度"
              type="number"
              :min="0"
              :step="0.1"
              :max="1"
            />
          </el-form-item>
        </el-form>
        <BoundaryMap
          ref="boundaryMap"
          :config="boundaryConfig"
          @change="handleBoundaryChange"
          :id="boundaryId"
        ></BoundaryMap>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="bsubmitForm">确 定</el-button>
            <el-button @click="bcancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {
  listMapData,
  getMapData,
  delMapData,
  addMapData,
  updateMapData,
} from '@/api/MapData/MapData'
import BoundaryMap from '@/components/BoundaryMap/index.vue'
import { ref, onMounted } from 'vue'
const { proxy } = getCurrentInstance()
const MapDataList = ref([])
const open = ref(false)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const loading = ref(false)
const boundaryMap = ref(null)
const boundaryId = ref(null)
const boundaryConfig = ref({
  id: null,
  title: '',
  color: '#1495E7',
  weight: 3,
  opacity: 0.5,
  fillColor: '#FFFFFF',
  fillOpacity: 0.5,
})
const form = ref({
  position: '',
  color: 'yellow',
  title: '',
  type: 'type1',
  content: '',
})
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  position: null,
  color: null,
  title: null,
  type: null,
  content: null,
})
const rules = ref({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  position: [{ required: true, message: '位置不能为空', trigger: 'blur' }],
})
var map = ''
onMounted(() => {
  getList()
})
// 添加标记
function addMarker(markerInfo) {
  //创建图片对象
  const position = markerInfo.position.split(',')
  var e = {
    lng: parseFloat(position[0]),
    lat: parseFloat(position[1]),
  }
  var icon = new T.Icon(selectIcon(markerInfo.color))
  //向地图上添加自定义标注
  var marker = new T.Marker(new T.LngLat(e.lng, e.lat), {
    icon: icon,
    zIndexOffset: 0,
  })
  marker.addEventListener('click', (e) => {
    console.log('点击了标记')
    document.getElementById('position').value = e.lng + ',' + e.lat
  })
  var label = new T.Label({
    text: `<p>${markerInfo.title}</p>`,
    position: new T.LngLat(e.lng, e.lat),
    offset: selectOffset(markerInfo.color),
  })
  label.setFontSize(16)
  label.setFontColor('white')
  label.setBackgroundColor('transparent')
  label.setBorderLine(0)
  // label.setBorderColor("none")
  map.addOverLay(marker)
  map.addOverLay(label)
}
// 选择图片
function selectImage(color) {
  switch (color) {
    case 'yellow':
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(2).png?sign=blt6bGAbCEu4eV1CV77jb0eFhUaDWRpiTrQy9v9kMzs=:0'
    case 'green':
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(3).png?sign=QgZmuKGt52ltFC0-3EKHG_oC0fgIaR_kYJt239Q9Fn4=:0'
    case 'blue':
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(1).png?sign=JZ5_f4AYa3GSK87HtYc85xyXz42KvrTH7tXm6gStyWA=:0'
    default:
      return 'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/icon%20(2).png?sign=blt6bGAbCEu4eV1CV77jb0eFhUaDWRpiTrQy9v9kMzs=:0'
  }
}
// 选择图标
function selectIcon(color) {
  switch (color) {
    case 'yellow':
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(150, 55),
        iconAnchor: new T.Point(30, 50),
      }
    case 'green':
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(150, 55),
        iconAnchor: new T.Point(20, 58),
      }
    case 'blue':
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(130, 65),
        iconAnchor: new T.Point(30, 60),
      }
    default:
      return {
        iconUrl: selectImage(color),
        iconSize: new T.Point(150, 55),
        iconAnchor: new T.Point(30, 50),
      }
  }
}
// 选择文字偏差
function selectOffset(color) {
  switch (color) {
    case 'yellow':
      return new T.Point(10, -43)
    case 'green':
      return new T.Point(5, -50)
    case 'blue':
      return new T.Point(0, -43)
    default:
      return new T.Point(10, -17)
  }
}
/** 查询地图列表 */
function getList() {
  loading.value = true
  listMapData(queryParams.value).then((response) => {
    MapDataList.value = response.rows
    MapDataList.value = MapDataList.value.slice(1)
    total.value = response.total - 1
    loading.value = false
    var zoom = 13
    const center = response.rows[0].position.split(',')
    const position = {
      lng: parseFloat(center[0]),
      lat: parseFloat(center[1]),
    }
    map = new T.Map('mapDiv')
    map.centerAndZoom(new T.LngLat(position.lng, position.lat), zoom)
    const imageURL =
      'http://t0.tianditu.gov.cn/img_w/wmts?' +
      'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
      '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=8bce5ceb483255b37a4aaa52bc86d11e'
    const imageURLT =
      'http://t0.tianditu.gov.cn/cia_w/wmts?' +
      'SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles' +
      '&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}' +
      '&tk=8bce5ceb483255b37a4aaa52bc86d11e'
    //创建自定义图层对象
    var lay = new T.TileLayer(imageURL, { minZoom: 1, maxZoom: 18 })
    var textLayer = new T.TileLayer(imageURLT, {
      minZoom: 1,
      maxZoom: 18,
    })
    //将图层增加到地图上
    map.addLayer(lay)
    map.addLayer(textLayer)
    var Menu = new T.ContextMenu({
      width: 100,
    })
    var _MenuItem3 = new T.MenuItem('添加标记', (e) => {
      form.value.id = null
      open.value = true
      title.value = '添加标记'
      form.value.position = e.lng + ',' + e.lat
    })
    Menu.addItem(_MenuItem3)
    var _MenuItem1 = new T.MenuItem('设置中心点', (e) => {
      form.value.id = 1
      form.value.position = e.lng + ',' + e.lat
      updateMapData(form.value).then((response) => {
        proxy.$modal.msgSuccess('设置成功')
      })
      map.centerAndZoom(new T.LngLat(e.lng, e.lat), zoom)
    })
    Menu.addItem(_MenuItem1)
    map.addContextMenu(Menu)
    function loadGeoJson() {
      var countries = []
      var countriesOverlay = new T.D3Overlay(init, redraw)
      d3.json(
        'https://ddns.ideal2077.com:5555/d/Handsomedog/shiliang/%E7%9F%B3%E6%A2%81%E9%95%87.geojson?sign=tqAPonliYDiMECn1umfHzl88RGiZMsxs_9MPGRfjbSs=:0',
        function (data) {
          countries = data.features
          map.addOverLay(countriesOverlay)
          countriesOverlay.bringToBack()
        }
      )
      function init(sel, transform) {
        var upd = sel.selectAll('path.geojson').data(countries)
        upd
          .enter()
          .append('path')
          .attr('class', 'geojson')
          .attr('stroke', 'black')
          .attr('fill', function (d, i) {
            return d3.hsl(Math.random() * 360, 0.9, 0.5)
          })
          .attr('fill-opacity', '0.5')
      }

      function redraw(sel, transform) {
        sel.selectAll('path.geojson').each(function (d, i) {
          d3.select(this).attr('d', transform.pathFromGeojson)
        })
      }
    }
    loadGeoJson()
    for (let i = 0; i < MapDataList.value.length; i++) {
      addMarker(MapDataList.value[i])
    }
    listBoundary({
      pageNum: 1,
      pageSize: 1000,
    }).then((response) => {
      const data = response.rows
      for (let i = 0; i < data.length; i++) {
        const item = data[i]
        const points = JSON.parse(item.position)
        const polygon = new T.Polygon(points, {
          color: item.color,
          weight: item.weight,
          opacity: item.opacity,
          fillColor: item.fillColor,
          fillOpacity: item.fillOpacity,
        })
        map.addOverLay(polygon)
      }
    })
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 表单重置
function reset() {
  form.value = {
    id: null,
    position: '',
    color: 'yellow',
    title: '',
    type: 'type1',
    content: '',
  }
  proxy.resetForm('MapDataRef')
}
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMapData(_id).then((response) => {
    form.value = response.data
    open.value = true
    title.value = '修改地图'
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['MapDataRef'].validate((valid) => {
    if (valid) {
      addMarker({
        position: form.value.position,
        color: form.value.color,
        title: form.value.title,
        type: form.value.type,
        content: form.value.content,
      })
      if (form.value.id != null) {
        updateMapData(form.value).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addMapData(form.value).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}
/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除地图编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delMapData(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

import {
  listBoundary,
  getBoundary,
  delBoundary,
  addBoundary,
  updateBoundary,
} from '@/api/boundary/boundary'
const boundaryList = ref([])
const btotal = ref(0)
const bopen = ref(false)
const bqueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  title: null,
  position: null,
  color: null,
  weight: null,
  opacity: null,
  fillColor: null,
  fillOpacity: null,
})

/** 查询边界表列表 */
function bgetList() {
  loading.value = true
  listBoundary(bqueryParams.value).then((response) => {
    boundaryList.value = response.rows
    btotal.value = response.total
    loading.value = false
  })
}

// 取消按钮
function bcancel() {
  bopen.value = false
  breset()
}

// 表单重置
function breset() {
  boundaryConfig.value = {
    id: null,
    title: '',
    color: '#1495E7',
    weight: 3,
    opacity: 0.5,
    fillColor: '#FFFFFF',
    fillOpacity: 0.5,
  }
  boundaryId.value = null
  boundaryPoints.value = []
  proxy.resetForm('boundaryRef')
}

function handleAdd() {
  breset()
  bopen.value = true
  title.value = '添加边界表'
  boundaryMap.value?.init()
}

/** 修改按钮操作 */
function bhandleUpdate(row) {
  breset()
  const _id = row.id || ids.value
  getBoundary(_id).then((response) => {
    boundaryConfig.value = response.data
    boundaryPoints.value = JSON.parse(response.data.position)
    boundaryMap.value?.init(_id)
    boundaryId.value = _id
    bopen.value = true
    title.value = '修改边界表'
  })
}

/** 提交按钮 */
function bsubmitForm() {
  proxy.$refs['boundaryRef'].validate((valid) => {
    if (valid) {
      if (boundaryConfig.value.id != null) {
        updateBoundary({
          ...boundaryConfig.value,
          position: JSON.stringify(boundaryPoints.value),
        }).then((response) => {
          proxy.$modal.msgSuccess('修改成功')
          bopen.value = false
          bgetList()
        })
      } else {
        addBoundary({
          ...boundaryConfig.value,
          position: JSON.stringify(boundaryPoints.value),
        }).then((response) => {
          proxy.$modal.msgSuccess('新增成功')
          bopen.value = false
          bgetList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function bhandleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除边界表编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delBoundary(_ids)
    })
    .then(() => {
      bgetList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
const boundaryPoints = ref([])
function handleBoundaryChange(points) {
  boundaryPoints.value = points
}
bgetList()
</script>
<style lang="scss" scoped>
#mapDiv {
  width: 1500px;
  height: 600px;
  margin: 10px auto;
}
.list {
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.position {
  display: flex;
  justify-content: center;
}
:deep(.tdt-label) {
  font-style: italic;
}
.color-preview {
  width: 100%;
  height: 40px;
  margin-top: 10px;
  img {
    height: 100%;
  }
}
.type-preview {
  width: 100%;
  height: 140px;
  margin-top: 10px;
}
</style>
